import { defineStore } from 'pinia'
import api from '@/http/index'
import { getToken, removeToken, setToken } from '@/common/auth'
import { Role_Enum } from '@/common/enum'

const useUserStore = defineStore('user', {
  state: () => ({
    user: {},
    token: getToken(),
    allRoles: [],
  }),
  actions: {
    login(data) {
      return new Promise((resolve, reject) => {
        api.auth
          .login(data)
          .then((res) => {
            this.token = res.data?.token
            setToken(this.token)
            resolve(this.token)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    register(data) {
      return new Promise((resolve, reject) => {
        api.auth
          .register(data)
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    async logout() {
      return new Promise((resolve, reject) => {
        try {
          removeToken()
          this.user = {}
          this.token = ''
          resolve()
        } catch (error) {
          reject(error)
        }
      })
    },
    async getUserInfo() {
      const res = await api.user.getUserInfo()
      this.user = res?.data || {}
      return this.user
    },
    async getAllRoles() {
      const res = await api.user.getRoles()
      this.allRoles = res.data
      return this.allRoles
    },
  },
  getters: {
    roles: (state) => state.user?.roles || [],
    roleIds() {
      return this.roles.map((role) => role.roleId)
    },
    isVisitor() {
      return this.roleIds.length === 1 && this.roleIds.includes(Role_Enum.sys_visitor)
    },
    checkRole() {
      return (roleIds) => {
        roleIds = Array.prototype.concat.call([], roleIds)
        return roleIds.every((roleId) => this.roleIds.includes(roleId))
      }
    },
  },
})

export default useUserStore
